<template>
  <div>
    <el-card>
      <el-button type="primary" @click="showCateDialog">添加分类</el-button>

      <!--表格 数据展示-->
      <zk-table class="treeTable" :data="tableData" :columns="columns" :selection-type="false" :show-index="true"
                :show-row-hover="false" index-text="#" border :expand-type="false">
        <!--  是否可用  -->
        <template #able="scopeInfo">
          <i v-if="!scopeInfo.row.cat_deleted" class="el-icon-success" style="color: lightgreen; font-size: 15px;"></i>
          <i v-else class="el-icon-error"></i>
        </template>
        <!-- level -->
        <template #level="scopeInfo">
          <el-tag v-if="scopeInfo.row.cat_level === 0">一级</el-tag>
          <el-tag v-else-if="scopeInfo.row.cat_level === 1" type="success">二级</el-tag>
          <el-tag v-else type="warning">三级</el-tag>
        </template>
        <!--  操作 -->
        <template #control="scopeInfo">
          <el-button type="primary" size="mini" @click="showEditDialog(scopeInfo.row.cat_id)">
            <i class="el-icon-edit"></i>
            <span>编辑</span>
          </el-button>
          <el-button type="danger" size="mini" @click="deleteCate(scopeInfo.row.cat_id)">
            <i class="el-icon-delete"></i>
            <span>删除</span>
          </el-button>
        </template>
      </zk-table>

      <!--分页-->
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="currentPage"
        :page-sizes="[3,5,10,20,30]"
        :page-size="dataSize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="dataTotal">
      </el-pagination>
    </el-card>

    <!--  添加分类 dialog  -->
    <el-dialog
      title="添加分类"
      :visible.sync="addCateDialogVisible"
      width="50%"
      @closed="handleClose">
      <el-form :model="addCateFrom" label-width="100px" :rules="addCateFromRules" ref="addCateFormRef">
        <el-form-item label="分类名称" prop="cat_name">
          <el-input v-model="addCateFrom.cat_name"></el-input>
        </el-form-item>
        <el-form-item label="父级分类">
          <el-cascader
            v-model="selectedKeys"
            :options="options"
            :props="{ expandTrigger: 'hover', value: 'cat_id' ,label: 'cat_name', children: 'children', checkStrictly: true}"
            :clearable="true"
            @change="handleChange"></el-cascader>
        </el-form-item>
      </el-form>
      <span slot="footer">
    <el-button @click="addCateDialogVisible = false">取 消</el-button>
    <el-button type="primary" @click="addCate">确 定</el-button>
  </span>
    </el-dialog>

    <!--  编辑分类 dialog  -->
    <el-dialog
      title="添加分类"
      :visible.sync="editCateDialogVisible"
      width="50%"
      @closed="handleClose">
      <el-form :model="editCateForm" label-width="100px" :rules="addCateFromRules" ref="editCateFormRef">
        <el-form-item label="分类名称" prop="cat_name">
          <el-input v-model="editCateForm.cat_name"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer">
    <el-button @click="editCateDialogVisible = false">取 消</el-button>
    <el-button type="primary" @click="editCate">确 定</el-button>
  </span>
    </el-dialog>
  </div>
</template>

<script>
import { apiGetCategories, apiAddCategory, apiDeleteCategory, apiEditCategory, apiGetCategory } from '@/api/index.js'

export default {
  name: 'Cate',
  created () {
    this.getCategories()
  },
  data () {
    return {
      tableData: [],
      dataTotal: 0,
      currentPage: 1,
      dataSize: 3,
      columns: [
        { label: '分类名称', prop: 'cat_name' },
        { label: '是否有效', type: 'template', template: 'able' },
        { label: '排序', type: 'template', template: 'level' },
        { label: '操作', type: 'template', template: 'control', width: '200px' }
      ],
      // 添加分类
      addCateDialogVisible: false,
      selectedKeys: [],
      addCateFrom: {
        cat_pid: 0,
        cat_name: '',
        cat_level: 0
      },
      addCateFromRules: {
        cat_name: [
          { required: true, message: '请输入分类名称', trigger: 'blur' }
        ]
      },
      options: [],
      // 编辑分类
      editCateDialogVisible: false,
      editCateForm: {
        id: 0,
        cat_name: ''
      }

    }
  },
  methods: {
    // 获取分类
    async getCategories () {
      const { data: res } = await apiGetCategories({
        pagenum: this.currentPage,
        pagesize: this.dataSize
      })
      if (res.meta.status !== 200) {
        return this.$message(res.meta.status, res.meta.msg)
      }
      this.tableData = res.data.result
      this.dataTotal = res.data.total
    },
    // 改变当前页显示数量
    handleSizeChange (val) {
      this.dataSize = val
      this.getCategories()
    },
    // 改变当前页数
    handleCurrentChange (val) {
      this.currentPage = val
      this.getCategories()
    },
    // 显示 添加dialog
    async showCateDialog () {
      this.addCateDialogVisible = true
      const { data: res } = await apiGetCategories({ type: 2 })
      if (res.meta.status !== 200) {
        return this.$message.error(res.meta.status, res.meta.msg)
      }
      this.options = res.data
    },
    // dialog 关闭
    handleClose () {
      // console.log(this.$refs)
      if (this.$refs.hasOwnProperty('addCateFormRef')) {
        this.$refs.addCateFormRef.resetFields()
      }
      if (this.$refs.hasOwnProperty('editCateFormRef')) {
        this.$refs.editCateFormRef.resetFields()
      }
    },
    //  数据改变
    handleChange () {
      if (this.selectedKeys.length > 0) {
        this.addCateFrom.cat_pid = this.selectedKeys[this.selectedKeys.length - 1]
        this.addCateFrom.cat_level = this.selectedKeys.length
      }
    },
    // 添加分类
    addCate () {
      this.$refs.addCateFormRef.validate(async valid => {
        if (!valid) return
        const { data: res } = await apiAddCategory(this.addCateFrom)
        if (res.meta.status !== 201) {
          return this.$message.error(res.meta.status, res.meta.msg)
        }
        this.$message.success('操作成功')
        this.addCateDialogVisible = false
        this.getCategories()
      })
    },
    // 删除分类
    async deleteCate (id) {
      let result = await this.$confirm('此操作将永久删除该分类, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        })
      })

      if (result !== 'confirm') return

      const { data: res } = await apiDeleteCategory(id)
      if (res.meta.status !== 200) {
        return this.$message.error(res.meta.status, res.meta.msg)
      }
      this.$message.success('删除成功')

      this.getCategories()
    },
    // 编辑 分类
    async showEditDialog (id) {
      this.editCateForm.id = id
      const { data: res } = await apiGetCategory(id)
      if (res.meta.status !== 200) {
        return this.$message.error(res.meta.status, res.meta.msg)
      }
      this.editCateForm.cat_name = res.data.cat_name
      this.editCateDialogVisible = true
    },
    editCate () {
      this.$refs.editCateFormRef.validate(async valid => {
        if (!valid) return false

        const { data: res } = await apiEditCategory(this.editCateForm)
        if (res.meta.status !== 200) {
          return this.$message.error(res.meta.status, res.meta.msg)
        }
        this.$message.success('操作成功')
        this.editCateDialogVisible = false
        this.getCategories()
      })
    }
  }
}
</script>

<style lang="less" scoped>
  .treeTable {
    margin-top: 15px;
  }

  .el-cascader {
    width: 100%;
  }
</style>
